package test.executor;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author Kent
 * @date 2022/8/9 9:11
 */
public class ThreadPoolDemo {
    private static final int CORE_POOL_SIZE = 5;
    private static final int MAX_IMUM_POOL_SIZE = 10;
    private static final Long KEEP_ALIVE_TIME = 0L;
    private static final int QUEUE_CAPACITY = 100;

    public static void main(String[] args) {
        ThreadPoolExecutor executor = new ThreadPoolExecutor(CORE_POOL_SIZE, MAX_IMUM_POOL_SIZE,
                KEEP_ALIVE_TIME, TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(QUEUE_CAPACITY),
                new ThreadPoolExecutor.DiscardOldestPolicy());
        /**
         *  指定不同的饱和策略(又名 饱和策略)
         *  new ThreadPoolExecutor.CallerRunsPolicy() 扩容队列，执行所有任务
         *  new ThreadPoolExecutor.AbortPolicy() 丢弃抛异常
         *  new ThreadPoolExecutor.DiscardPolicy() 丢弃不抛异常
         *  new ThreadPoolExecutor.DiscardOldestPolicy() 丢弃最早进入队列的未处理的请求
         */

        for (int i = 0; i < 1000; i++) {
            Task task = new Task("" + i);
            // 执行Runnable
            executor.execute(task);
        }
        //终止线程池
        executor.shutdown();
        while (!executor.isTerminated()) {

        }

        System.out.println("Finished all threads");
    }
}
